

#include "lfs.h"
#include "lfs_flashbd.h"

#define BLOCK_COUNT 16
#define BLOCK_SIZE 4096
#define CACHE_SIZE 128
#define READ_SIZE CACHE_SIZE
#define PROG_SIZE CACHE_SIZE
#define LOOKAHEAD_SIZE 16
#define BLOCK_CYCLES 500

// variables used by the filesystem
lfs_t lfs;

static uint32_t read_buffer[CACHE_SIZE/sizeof(uint32_t)];
static uint32_t prog_buffer[CACHE_SIZE/sizeof(uint32_t)];
static uint8_t lookahead_buffer[LOOKAHEAD_SIZE];

const struct lfs_config cfg = {
    // block device operations
    .read  = lfs_flashbd_read,
    .prog  = lfs_flashbd_prog,
    .erase = lfs_flashbd_erase,
    .sync  = lfs_flashbd_sync,

    // block device configuration
    .read_size = READ_SIZE,
    .prog_size = PROG_SIZE,
    .block_size = BLOCK_SIZE,
    .block_count = BLOCK_COUNT,
    .cache_size = CACHE_SIZE,
    .lookahead_size = LOOKAHEAD_SIZE,
    .block_cycles = BLOCK_CYCLES,

    .read_buffer = read_buffer,
    .prog_buffer = prog_buffer,
    .lookahead_buffer = lookahead_buffer,    
};


int lfs_setup(void) {
    // mount the filesystem
    int err = lfs_mount(&lfs, &cfg);
    // reformat if we can't mount the filesystem
    // this should only happen on the first boot
    if (err) {
        lfs_format(&lfs, &cfg);
        err = lfs_mount(&lfs, &cfg);
    }
    return err;
}

int lfs_format2(void){
    return lfs_format(&lfs, &cfg);
}